<template>
    <div>
        <el-card style="margin-bottom: 10px;">
            <!--<CategorySelector @idChange="idChange" :disabled="!showList"></CategorySelector>-->
            <CategorySelector @idChange="idChange" ref="cs"></CategorySelector>
        </el-card>

        <!-- v-if进行渲染,会将整个dom全部删除,因此v-if不能和template一起使用,template需要后续js进行解析才能展示 -->
        <el-card v-show="showList" v-loading="loading">
            <el-button :disabled="!category3Id" @click="showAdd" type="primary" icon="el-icon-plus">添加属性</el-button>

            <!--
                el-table中el-table-column每一个属性列,row表示一个属性行,当渲染简单数据可以直接使用el-table-column
                当渲染复杂数据时,需要使用插槽形式
            -->
            <el-table border :data="attrs">
                <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>

                <el-table-column align="center" prop="attrName" label="属性名称"></el-table-column>

                <el-table-column label="属性值列表" align="center">
                    <template slot-scope="{row,$index}">
                        <el-tag :key="attrValue.id" v-for="attrValue in row.attrValueList" style="margin:0 5px 5px 0">
                            {{attrValue.valueName}}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="操作">
                    <template slot-scope="{row,$index}">
                        <HintButton @click="showEdit(row)" title="修改" type="warning" icon="el-icon-edit" size="mini" style="margin-right: 5px"></HintButton>
                        <el-popconfirm :title="`确定删除${row.attrName}吗？`" @onConfirm="delAttr(row)">
                            <HintButton slot="reference" title="删除" type="danger" icon="el-icon-delete" size="mini"></HintButton>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-card v-show="!showList">
            <el-form inline>
                <el-form-item label="属性名">
                    <el-input v-model="attr.attrName" placeholder="请输入属性名"></el-input>
                </el-form-item>
            </el-form>

            <el-button @click="addAttrValue" :disabled="!attr.attrName" type="primary" icon="el-icon-plus">添加属性值</el-button>
            <el-button @click="showList=true;flagForAddFail=false">取消</el-button>

            <el-table border style="margin: 20px 0" :data="attr.attrValueList">
                <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>

                <el-table-column label="属性值名称">
                    <!-- 浏览器第一次上来是看不到template,需要后续js进行解析才能看到,因此我们要使用v-show进行判断,而不能使用v-if -->
                    <template slot-scope="{row,$index}">
                        <span style="display: block;" @click="toEdit(row,$index)" v-if="!row.isEdit">{{row.valueName}}</span>
                        <el-input @keyup.enter.native="toSpan(row)" @blur="toSpan(row)" :ref="`input${$index}`"
                                  v-model="row.valueName" size="mini" v-else></el-input>
                    </template>
                </el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="{row,$index}">
                        <el-popconfirm :title="`确定要删除${row.valueName}吗？`"
                                       @onConfirm="attr.attrValueList.splice($index,1)" >
                            <HintButton title="删除" slot="reference" type="danger" icon="el-icon-delete"
                                       size="mini">删除</HintButton>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-button type="primary" :disabled="disableForSave" @click="save">保存</el-button>
            <el-button @click="showList=true;flagForAddFail=false">取消</el-button>
        </el-card>
    </div>
</template>

<script>
    import cloneDeep from 'lodash/cloneDeep'
    export default {
        data() {
            return {
                category1Id: '',
                category2Id: '',
                category3Id: '',
                attrs: [],
                attr: {             // 代表当前编辑/添加的属性
                    attrName: '',
                    attrValueList: [],
                },
                showList: true,     // 代表属性列表界面是否隐藏

                flagForAddFail: false,

                loading: false,
            }
        },
        methods: {
            // 三级分类id变化时,父子组件传值函数
            idChange({id,level}) {
                if(level === 1) {
                    this.category1Id = id;
                    this.category3Id = '';
                    this.category2Id = '';
                    this.attrs = [];
                }else if(level === 2) {
                    this.category3Id = '';
                    this.category2Id = id;
                    this.attrs = [];
                }else {
                    this.category3Id = id;

                    this.getAttr();
                }
            },

            // 获取属性列表
            async getAttr() {
                this.loading = true;
                const {code,data} = await this.$API.attrs.getAttrs(this.category1Id,this.category2Id,this.category3Id);
                if(code === 200) {
                    this.loading = false;
                    this.attrs = data;
                }
            },

            // 修改按钮修改函数
            showEdit(row) {
                this.showList = false;

                this.attr = cloneDeep(row);
            },

            // 点击添加按钮实现添加功能
            showAdd() {
                this.showList = false;

                this.attr = {
                    attrName: '',
                    attrValueList: [],
                };
            },

            // 为对应的属性添加属性值
            addAttrValue() {
                if(this.flagForAddFail) {
                    return;
                }
                const value = {
                    valueName: '',
                    isEdit: true,       // 让属性值对应的界面处于编辑状态
                };

                this.attr.attrValueList.push(value);

                // 让对应的input(最新)选中
                this.$nextTick(() => {
                    this.$refs[`input${this.attr.attrValueList.length-1}`].focus();
                });
            },

            // 编辑转换为显示操作
            toSpan(row) {
                // 如果为空或者有重复值时不让切换
                if(!row.valueName.trim()) {
                    this.$message({
                        message: '不能输入空值',
                        type: 'error',
                    });
                    this.flagForAddFail = true;
                    return;
                }

                const res = this.attr.attrValueList.filter((item) => {
                    if(item.valueName === row.valueName) {
                        return item;
                    }
                });

                if(res.length >= 2) {
                    this.$message({
                        message: '不能输入重复值',
                        type: 'error',
                    });
                    this.flagForAddFail = true;
                    return;
                }

                this.flagForAddFail = false;
                row.isEdit = false;
            },

            // 显示转换为编辑操作
            toEdit(row,index) {
                if(this.flagForAddFail) return;

                if(row.hasOwnProperty('isEdit')) {
                    row.isEdit = true;
                }else {
                    this.$set(row,'isEdit',true);
                }

                this.$nextTick(() => {
                    this.$refs[`input${index}`].focus();
                });
            },

            // 添加或修改属性操作
            async save() {
                let attr = {
                    ...this.attr,
                    categoryId: this.category3Id,
                    categoryLevel: 3,
                };

                const {code} = await this.$API.attrs.addOrUpdateArr(attr);

                if(code === 200) {
                    this.$message({
                        message: '添加成功',
                        type: 'success',
                    });
                    await this.getAttr();
                    this.showList = true;
                }
            },

            // 删除属性操作
            async delAttr(row) {
                const {code} = await this.$API.attrs.delAttrById(row.id);
                if(code === 200) {
                    this.$message({
                        message: '删除成功',
                        type: 'success',
                    });

                    this.getAttr();
                }
            }

        },

        computed: {
            disableForSave() {
                // 输入框为空或输入框的内容重复时,保存按钮也得禁用
                let flagForAddFail = false;
                let index = this.attr.attrValueList.length-1;
                if(index>=0) {
                    let valueName = this.attr.attrValueList[index].valueName;
                    let dog1 = valueName.trim();
                    let dog2 = this.attr.attrValueList.filter(attrValue => attrValue.valueName === valueName);
                    if(dog1=== '' || dog2.length >= 2) {
                        flagForAddFail = true;
                    }
                }else {
                    flagForAddFail = true;
                }

                return this.attr.attrValueList.length===0||!this.attr.attrName || flagForAddFail
            }
        },

        watch: {
            showList(val) {
                this.$refs.cs.disabled = !val;
            }
        },

        name: "Attr",
    }
</script>

<style>
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>
